package cn.lblbc.webbrowser

import android.app.AlertDialog
import android.app.DownloadManager
import android.content.BroadcastReceiver
import android.content.Context
import android.content.Intent
import android.content.IntentFilter
import android.database.Cursor
import android.net.Uri
import android.os.Build
import android.os.Bundle
import android.os.Environment
import android.os.Handler
import android.os.Looper
import android.util.Log
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.Button
import android.widget.ImageButton
import android.widget.LinearLayout
import android.widget.ProgressBar
import android.widget.TextView
import android.widget.Toast
import androidx.appcompat.app.AppCompatActivity
import androidx.core.content.FileProvider
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import cn.lblbc.webbrowser.utils.CompletedDownloadManager
import cn.lblbc.webbrowser.utils.CustomDownloader
import java.io.File
import java.text.SimpleDateFormat
import java.util.Date
import java.util.Locale

/**
 * 下载文件列表Activity
 */
class DownloadsActivity : BaseActivity() {
    private lateinit var recyclerView: RecyclerView
    private lateinit var emptyView: LinearLayout
    private lateinit var downloadManager: DownloadManager
    private lateinit var adapter: DownloadsAdapter
    private var refreshHandler = Handler(Looper.getMainLooper())
    private lateinit var refreshRunnable: Runnable
    private val REFRESH_INTERVAL = 500L // 0.5秒刷新一次，提高刷新频率

    // 自定义下载器和完成的下载管理器实例
    private var customDownloader: CustomDownloader? = null
    private var completedDownloadManager: CompletedDownloadManager? = null

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_downloads)

        downloadManager = getSystemService(Context.DOWNLOAD_SERVICE) as DownloadManager

        // 初始化自定义下载器和完成的下载管理器
        customDownloader = (application as? BrowserApplication)?.customDownloader
        completedDownloadManager = (application as? BrowserApplication)?.completedDownloadManager
        println("【下载列表】自定义下载器: ${customDownloader != null}")
        println("【下载列表】完成的下载管理器: ${completedDownloadManager != null}")

        recyclerView = findViewById(R.id.downloadsRecyclerView)
        emptyView = findViewById(R.id.emptyView)

        // 设置返回按钮
        findViewById<ImageButton>(R.id.backButton).setOnClickListener {
            finish()
        }

        // 设置删除全部按钮
        findViewById<ImageButton>(R.id.deleteAllButton).setOnClickListener {
            showDeleteAllConfirmDialog()
        }

        setupRecyclerView()
        setupRefreshTask()
        loadDownloads()
    }

    override fun onResume() {
        super.onResume()
        startRefreshTask()
    }

    override fun onPause() {
        super.onPause()
        stopRefreshTask()
    }

    private fun setupRefreshTask() {
        refreshRunnable = Runnable {
            loadDownloads()
            refreshHandler.postDelayed(refreshRunnable, REFRESH_INTERVAL)
        }
    }

    private fun startRefreshTask() {
        // 先停止之前的任务，避免重复
        stopRefreshTask()
        // 立即执行一次，然后定期执行
        loadDownloads()
        refreshHandler.postDelayed(refreshRunnable, REFRESH_INTERVAL)
    }

    private fun stopRefreshTask() {
        refreshHandler.removeCallbacks(refreshRunnable)
    }

    private fun setupRecyclerView() {
        recyclerView.layoutManager = LinearLayoutManager(this)
        adapter = DownloadsAdapter(
            onItemClick = { downloadItem ->
                openDownloadedFile(downloadItem)
            },
            onPauseClick = { downloadItem ->
                pauseDownload(downloadItem)
            },
            onResumeClick = { downloadItem ->
                resumeDownload(downloadItem)
            },
            onDeleteClick = { downloadItem ->
                showDeleteConfirmDialog(downloadItem)
            }
        )
        recyclerView.adapter = adapter
    }

    private fun loadDownloads() {
        val downloadItems = getDownloadedFiles()

        // 更新UI
        if (downloadItems.isEmpty()) {
            recyclerView.visibility = View.GONE
            emptyView.visibility = View.VISIBLE
        } else {
            recyclerView.visibility = View.VISIBLE
            emptyView.visibility = View.GONE
            adapter.updateData(downloadItems)
        }
    }

    private fun getDownloadedFiles(): List<DownloadItem> {
        val downloadItems = mutableListOf<DownloadItem>()

        try {
            // 1. 获取系统DownloadManager中的下载项
            val query = DownloadManager.Query()
            val cursor = downloadManager.query(query)

            if (cursor != null) {
                while (cursor.moveToNext()) {
                    try {
                        val idIndex = cursor.getColumnIndex(DownloadManager.COLUMN_ID)
                        val titleIndex = cursor.getColumnIndex(DownloadManager.COLUMN_TITLE)
                        val statusIndex = cursor.getColumnIndex(DownloadManager.COLUMN_STATUS)
                        val bytesTotalIndex = cursor.getColumnIndex(DownloadManager.COLUMN_TOTAL_SIZE_BYTES)
                        val bytesDownloadedIndex = cursor.getColumnIndex(DownloadManager.COLUMN_BYTES_DOWNLOADED_SO_FAR)
                        val uriIndex = cursor.getColumnIndex(DownloadManager.COLUMN_LOCAL_URI)

                        if (idIndex != -1 && titleIndex != -1 && statusIndex != -1 &&
                            bytesTotalIndex != -1 && bytesDownloadedIndex != -1) {

                            val id = cursor.getLong(idIndex)
                            val title = cursor.getString(titleIndex) ?: "未知文件"
                            val status = cursor.getInt(statusIndex)
                            val bytesTotal = cursor.getLong(bytesTotalIndex)
                            val bytesDownloaded = cursor.getLong(bytesDownloadedIndex)
                            val localUri = if (uriIndex != -1) cursor.getString(uriIndex) else null

                            // 获取文件路径
                            var filePath = ""
                            var fileExists = false

                            if (localUri != null) {
                                try {
                                    val uri = Uri.parse(localUri)
                                    val file = File(uri.path ?: "")
                                    if (file.exists()) {
                                        fileExists = true
                                        filePath = file.absolutePath
                                    }
                                } catch (e: Exception) {
                                    e.printStackTrace()
                                }
                            }

                            // 如果文件路径为空，尝试在下载目录中查找
                            if (filePath.isEmpty()) {
                                // 检查公共下载目录
                                val publicDownloadFile = File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS), title)
                                if (publicDownloadFile.exists()) {
                                    fileExists = true
                                    filePath = publicDownloadFile.absolutePath
                                } else if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) {
                                    // Android 13+ 检查应用专用下载目录
                                    val appDownloadFile = File(getExternalFilesDir(Environment.DIRECTORY_DOWNLOADS), title)
                                    if (appDownloadFile.exists()) {
                                        fileExists = true
                                        filePath = appDownloadFile.absolutePath
                                    }
                                }
                            }

                            // 计算下载进度
                            val progress = if (bytesTotal > 0) {
                                (bytesDownloaded * 100 / bytesTotal).toInt()
                            } else {
                                0
                            }

                            // 创建下载项
                            val downloadItem = DownloadItem(
                                id = id,
                                title = title,
                                status = status,
                                bytesDownloaded = bytesDownloaded,
                                bytesTotal = bytesTotal,
                                progress = progress,
                                filePath = filePath,
                                fileExists = fileExists,
                                isCustomDownload = false
                            )

                            downloadItems.add(downloadItem)

                            // 打印下载项信息
                            Log.d("下载项", "$title, 状态: $status, 进度: $bytesDownloaded/$bytesTotal")
                        }
                    } catch (e: Exception) {
                        e.printStackTrace()
                    }
                }
                cursor.close()
            }

            // 2. 获取自定义下载器中的下载项
            customDownloader?.getActiveDownloads()?.forEach { downloadTask ->
                try {
                    // 计算下载进度
                    val progress = if (downloadTask.totalSize > 0) {
                        (downloadTask.downloadedSize * 100 / downloadTask.totalSize).toInt()
                    } else {
                        0
                    }

                    // 创建下载项
                    val downloadItem = DownloadItem(
                        id = downloadTask.id,
                        title = downloadTask.fileName,
                        status = DownloadManager.STATUS_RUNNING, // 自定义下载器中的下载项都是正在下载的
                        bytesDownloaded = downloadTask.downloadedSize,
                        bytesTotal = downloadTask.totalSize,
                        progress = progress,
                        filePath = downloadTask.file.absolutePath,
                        fileExists = downloadTask.file.exists(),
                        isCustomDownload = true
                    )

                    downloadItems.add(downloadItem)

                    // 打印下载项信息
                    Log.d("自定义下载项", "${downloadTask.fileName}, 进度: ${downloadTask.downloadedSize}/${downloadTask.totalSize}")
                } catch (e: Exception) {
                    e.printStackTrace()
                }
            }

            // 3. 获取暂停的下载项
            val pausedDownloads = PausedDownloadInfo.getAllPausedDownloads(this)
            pausedDownloads.forEach { pausedDownload ->
                try {
                    // 创建下载项
                    val downloadItem = DownloadItem(
                        id = pausedDownload.id,
                        title = pausedDownload.title,
                        status = DownloadManager.STATUS_PAUSED,
                        bytesDownloaded = pausedDownload.bytesDownloaded,
                        bytesTotal = pausedDownload.bytesTotal,
                        progress = pausedDownload.progress,
                        filePath = pausedDownload.filePath,
                        fileExists = File(pausedDownload.filePath).exists(),
                        isCustomDownload = pausedDownload.isCustomDownload
                    )

                    downloadItems.add(downloadItem)

                    // 打印下载项信息
                    Log.d("暂停的下载项", "${pausedDownload.title}, 进度: ${pausedDownload.bytesDownloaded}/${pausedDownload.bytesTotal}")
                } catch (e: Exception) {
                    e.printStackTrace()
                }
            }

            // 4. 获取完成的下载项
            completedDownloadManager?.getAllCompletedDownloads()?.forEach { completedDownload ->
                try {
                    // 创建下载项
                    val downloadItem = DownloadItem(
                        id = completedDownload.id,
                        title = completedDownload.fileName,
                        status = DownloadManager.STATUS_SUCCESSFUL,
                        bytesDownloaded = completedDownload.fileSize,
                        bytesTotal = completedDownload.fileSize,
                        progress = 100,
                        filePath = completedDownload.filePath,
                        fileExists = File(completedDownload.filePath).exists(),
                        isCustomDownload = true
                    )

                    downloadItems.add(downloadItem)
                } catch (e: Exception) {
                    e.printStackTrace()
                }
            }

        } catch (e: Exception) {
            e.printStackTrace()
        }

        return downloadItems
    }

    private fun openDownloadedFile(downloadItem: DownloadItem) {
        try {
            if (!downloadItem.fileExists) {
                Toast.makeText(this, "文件不存在", Toast.LENGTH_SHORT).show()
                return
            }

            val file = File(downloadItem.filePath)
            if (!file.exists()) {
                Toast.makeText(this, "文件不存在", Toast.LENGTH_SHORT).show()
                return
            }

            val uri = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
                FileProvider.getUriForFile(
                    this,
                    "${packageName}.fileprovider",
                    file
                )
            } else {
                Uri.fromFile(file)
            }

            val intent = Intent(Intent.ACTION_VIEW)
            intent.setDataAndType(uri, getMimeType(file.name))
            intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION)

            try {
                startActivity(intent)
            } catch (e: Exception) {
                Toast.makeText(this, "没有应用可以打开此文件", Toast.LENGTH_SHORT).show()
                e.printStackTrace()
            }
        } catch (e: Exception) {
            Toast.makeText(this, "打开文件失败: ${e.message}", Toast.LENGTH_SHORT).show()
            e.printStackTrace()
        }
    }

    private fun getMimeType(fileName: String): String {
        return when {
            fileName.endsWith(".pdf") -> "application/pdf"
            fileName.endsWith(".doc") || fileName.endsWith(".docx") -> "application/msword"
            fileName.endsWith(".xls") || fileName.endsWith(".xlsx") -> "application/vnd.ms-excel"
            fileName.endsWith(".ppt") || fileName.endsWith(".pptx") -> "application/vnd.ms-powerpoint"
            fileName.endsWith(".zip") -> "application/zip"
            fileName.endsWith(".rar") -> "application/x-rar-compressed"
            fileName.endsWith(".apk") -> "application/vnd.android.package-archive"
            fileName.endsWith(".txt") -> "text/plain"
            fileName.endsWith(".jpg") || fileName.endsWith(".jpeg") -> "image/jpeg"
            fileName.endsWith(".png") -> "image/png"
            fileName.endsWith(".gif") -> "image/gif"
            fileName.endsWith(".mp3") -> "audio/mp3"
            fileName.endsWith(".mp4") -> "video/mp4"
            else -> "*/*"
        }
    }

    private fun pauseDownload(downloadItem: DownloadItem) {
        try {
            if (downloadItem.isCustomDownload) {
                // 暂停自定义下载器中的下载
                Toast.makeText(this, "暂停功能暂不支持自定义下载", Toast.LENGTH_SHORT).show()
                return
            }

            // 保存下载信息
            val pausedDownloadInfo = PausedDownloadInfo(
                id = downloadItem.id,
                url = "", // 暂时无法获取URL
                title = downloadItem.title,
                bytesDownloaded = downloadItem.bytesDownloaded,
                bytesTotal = downloadItem.bytesTotal,
                progress = downloadItem.progress,
                filePath = downloadItem.filePath,
                isCustomDownload = downloadItem.isCustomDownload
            )

            // 保存暂停的下载信息
            pausedDownloadInfo.save(this)

            // 从下载管理器中移除下载
            downloadManager.remove(downloadItem.id)

            // 刷新列表
            loadDownloads()

            Toast.makeText(this, "已暂停下载", Toast.LENGTH_SHORT).show()
        } catch (e: Exception) {
            Toast.makeText(this, "暂停下载失败: ${e.message}", Toast.LENGTH_SHORT).show()
            e.printStackTrace()
        }
    }

    private fun resumeDownload(downloadItem: DownloadItem) {
        try {
            // 获取暂停的下载信息
            val pausedDownloadInfo = PausedDownloadInfo.getPausedDownload(this, downloadItem.id)

            if (pausedDownloadInfo == null) {
                Toast.makeText(this, "无法恢复下载，找不到下载信息", Toast.LENGTH_SHORT).show()
                return
            }

            // 如果是自定义下载，使用自定义下载器恢复
            if (pausedDownloadInfo.isCustomDownload) {
                Toast.makeText(this, "恢复功能暂不支持自定义下载", Toast.LENGTH_SHORT).show()
                return
            }

            // 从暂停的下载列表中移除
            PausedDownloadInfo.removePausedDownload(this, downloadItem.id)

            // 刷新列表
            loadDownloads()

            Toast.makeText(this, "已恢复下载", Toast.LENGTH_SHORT).show()
        } catch (e: Exception) {
            Toast.makeText(this, "恢复下载失败: ${e.message}", Toast.LENGTH_SHORT).show()
            e.printStackTrace()
        }
    }

    private fun deleteDownload(downloadItem: DownloadItem) {
        try {
            if (downloadItem.isCustomDownload) {
                // 如果是完成的下载，从完成的下载列表中移除
                if (downloadItem.status == DownloadManager.STATUS_SUCCESSFUL) {
                    completedDownloadManager?.removeCompletedDownload(downloadItem.id)
                } else {
                    // 目前自定义下载器不支持删除正在进行的下载
                    Toast.makeText(this, "删除功能暂不支持正在进行的自定义下载", Toast.LENGTH_SHORT).show()
                    return
                }
            }

            // 如果是暂停的下载，从暂停的下载列表中移除
            PausedDownloadInfo.removePausedDownload(this, downloadItem.id)

            // 如果是系统下载管理器中的下载，从下载管理器中移除
            if (downloadItem.status != DownloadManager.STATUS_PAUSED) {
                downloadManager.remove(downloadItem.id)
            }

            // 删除文件
            if (downloadItem.fileExists) {
                val file = File(downloadItem.filePath)
                if (file.exists()) {
                    val deleted = file.delete()
                    if (!deleted) {
                        Toast.makeText(this, "无法删除文件", Toast.LENGTH_SHORT).show()
                    }
                }
            }

            // 刷新列表
            loadDownloads()

            Toast.makeText(this, "已删除下载", Toast.LENGTH_SHORT).show()
        } catch (e: Exception) {
            Toast.makeText(this, "删除下载失败: ${e.message}", Toast.LENGTH_SHORT).show()
            e.printStackTrace()
        }
    }

    private fun deleteAllDownloads() {
        try {
            // 获取所有下载项
            val downloadItems = getDownloadedFiles()

            // 删除所有下载项
            for (downloadItem in downloadItems) {
                deleteDownload(downloadItem)
            }

            // 删除所有完成的下载项
            completedDownloadManager?.removeAllCompletedDownloads()

            // 刷新列表
            loadDownloads()

            Toast.makeText(this, "已删除所有下载", Toast.LENGTH_SHORT).show()
        } catch (e: Exception) {
            Toast.makeText(this, "删除所有下载失败: ${e.message}", Toast.LENGTH_SHORT).show()
            e.printStackTrace()
        }
    }

    private fun showDeleteConfirmDialog(downloadItem: DownloadItem) {
        AlertDialog.Builder(this)
            .setTitle("删除下载")
            .setMessage("确定要删除\"${downloadItem.title}\"吗？")
            .setPositiveButton("删除") { _, _ ->
                deleteDownload(downloadItem)
            }
            .setNegativeButton("取消", null)
            .show()
    }

    private fun showDeleteAllConfirmDialog() {
        AlertDialog.Builder(this)
            .setTitle("删除所有下载")
            .setMessage("确定要删除所有下载吗？")
            .setPositiveButton("删除") { _, _ ->
                deleteAllDownloads()
            }
            .setNegativeButton("取消", null)
            .show()
    }

    /**
     * 格式化文件大小
     */
    private fun formatFileSize(size: Long): String {
        if (size <= 0) return "0 B"

        val units = arrayOf("B", "KB", "MB", "GB", "TB")
        val digitGroups = (Math.log10(size.toDouble()) / Math.log10(1024.0)).toInt()

        return String.format("%.1f %s", size / Math.pow(1024.0, digitGroups.toDouble()), units[digitGroups])
    }

    /**
     * 下载项数据类
     */
    data class DownloadItem(
        val id: Long,
        val title: String,
        val status: Int,
        val bytesDownloaded: Long,
        val bytesTotal: Long,
        val progress: Int,
        val filePath: String,
        val fileExists: Boolean,
        val isCustomDownload: Boolean
    )

    /**
     * 暂停的下载信息数据类
     */
    data class PausedDownloadInfo(
        val id: Long,
        val url: String,
        val title: String,
        val bytesDownloaded: Long,
        val bytesTotal: Long,
        val progress: Int,
        val filePath: String,
        val isCustomDownload: Boolean
    ) {
        /**
         * 保存暂停的下载信息
         */
        fun save(context: Context?) {
            if (context == null) return

            try {
                // 获取已有的暂停下载列表
                val pausedDownloads = getAllPausedDownloads(context).toMutableList()

                // 移除相同ID的下载
                pausedDownloads.removeAll { it.id == id }

                // 添加新的暂停下载
                pausedDownloads.add(this)

                // 保存到SharedPreferences
                val sharedPrefs = context.getSharedPreferences(PREFS_NAME, Context.MODE_PRIVATE)
                val editor = sharedPrefs.edit()

                // 将列表转换为JSON字符串
                val json = pausedDownloads.joinToString(separator = SEPARATOR) { it.toJsonString() }

                // 保存JSON字符串
                editor.putString(PAUSED_DOWNLOADS_KEY, json)
                editor.apply()
            } catch (e: Exception) {
                e.printStackTrace()
            }
        }

        /**
         * 将暂停的下载信息转换为JSON字符串
         */
        private fun toJsonString(): String {
            return "$id|$url|$title|$bytesDownloaded|$bytesTotal|$progress|$filePath|$isCustomDownload"
        }

        companion object {
            private const val PREFS_NAME = "download_prefs"
            private const val PAUSED_DOWNLOADS_KEY = "paused_downloads"
            private const val SEPARATOR = "###"

            /**
             * 获取所有暂停的下载信息
             */
            fun getAllPausedDownloads(context: Context?): List<PausedDownloadInfo> {
                if (context == null) return emptyList()

                try {
                    val sharedPrefs = context.getSharedPreferences(PREFS_NAME, Context.MODE_PRIVATE)
                    val json = sharedPrefs.getString(PAUSED_DOWNLOADS_KEY, "") ?: ""

                    if (json.isEmpty()) return emptyList()

                    // 将JSON字符串转换为暂停下载列表
                    return json.split(SEPARATOR).mapNotNull { jsonString ->
                        try {
                            val parts = jsonString.split("|")
                            if (parts.size >= 8) {
                                PausedDownloadInfo(
                                    id = parts[0].toLong(),
                                    url = parts[1],
                                    title = parts[2],
                                    bytesDownloaded = parts[3].toLong(),
                                    bytesTotal = parts[4].toLong(),
                                    progress = parts[5].toInt(),
                                    filePath = parts[6],
                                    isCustomDownload = parts[7].toBoolean()
                                )
                            } else {
                                null
                            }
                        } catch (e: Exception) {
                            e.printStackTrace()
                            null
                        }
                    }
                } catch (e: Exception) {
                    e.printStackTrace()
                    return emptyList()
                }
            }

            /**
             * 获取指定ID的暂停下载信息
             */
            fun getPausedDownload(context: Context?, id: Long): PausedDownloadInfo? {
                return getAllPausedDownloads(context).find { it.id == id }
            }

            /**
             * 移除指定ID的暂停下载信息
             */
            fun removePausedDownload(context: Context?, id: Long) {
                if (context == null) return

                try {
                    // 获取已有的暂停下载列表
                    val pausedDownloads = getAllPausedDownloads(context).toMutableList()

                    // 移除指定ID的下载
                    pausedDownloads.removeAll { it.id == id }

                    // 保存到SharedPreferences
                    val sharedPrefs = context.getSharedPreferences(PREFS_NAME, Context.MODE_PRIVATE)
                    val editor = sharedPrefs.edit()

                    // 将列表转换为JSON字符串
                    val json = pausedDownloads.joinToString(separator = SEPARATOR) { it.toJsonString() }

                    // 保存JSON字符串
                    editor.putString(PAUSED_DOWNLOADS_KEY, json)
                    editor.apply()
                } catch (e: Exception) {
                    e.printStackTrace()
                }
            }
        }
    }

    /**
     * 下载列表适配器
     */
    inner class DownloadsAdapter(
        private val onItemClick: (DownloadItem) -> Unit,
        private val onPauseClick: (DownloadItem) -> Unit,
        private val onResumeClick: (DownloadItem) -> Unit,
        private val onDeleteClick: (DownloadItem) -> Unit
    ) : RecyclerView.Adapter<DownloadsAdapter.ViewHolder>() {

        private val downloadItems = mutableListOf<DownloadItem>()

        fun updateData(newItems: List<DownloadItem>) {
            downloadItems.clear()
            downloadItems.addAll(newItems)
            notifyDataSetChanged()
        }

        override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder {
            val view = LayoutInflater.from(parent.context).inflate(R.layout.item_download, parent, false)
            return ViewHolder(view)
        }

        override fun onBindViewHolder(holder: ViewHolder, position: Int) {
            val downloadItem = downloadItems[position]
            holder.bind(downloadItem)
        }

        override fun getItemCount(): Int = downloadItems.size

        inner class ViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView) {
            private val titleTextView: TextView = itemView.findViewById(R.id.downloadTitle)
            private val statusTextView: TextView = itemView.findViewById(R.id.downloadStatus)
            private val progressBar: ProgressBar = itemView.findViewById(R.id.downloadProgressBar)
            private val sizeTextView: TextView = itemView.findViewById(R.id.downloadSize)
            private val dateTextView: TextView = itemView.findViewById(R.id.downloadDate)
            private val actionsLayout: LinearLayout = itemView.findViewById(R.id.downloadActions)
            private val pauseResumeButton: ImageButton = itemView.findViewById(R.id.pauseResumeButton)
            private val deleteButton: ImageButton = itemView.findViewById(R.id.deleteButton)

            fun bind(downloadItem: DownloadItem) {
                titleTextView.text = downloadItem.title

                // 设置状态文本
                val statusText = when (downloadItem.status) {
                    DownloadManager.STATUS_PENDING -> "等待中"
                    DownloadManager.STATUS_RUNNING -> {
                        val progress = if (downloadItem.bytesTotal > 0) {
                            "${downloadItem.progress}%"
                        } else {
                            "下载中"
                        }
                        progress
                    }
                    DownloadManager.STATUS_PAUSED -> "已暂停"
                    DownloadManager.STATUS_SUCCESSFUL -> "已完成"
                    DownloadManager.STATUS_FAILED -> "下载失败"
                    else -> "未知状态"
                }
                statusTextView.text = statusText
                statusTextView.visibility = View.VISIBLE

                // 设置文件大小
                val sizeText = if (downloadItem.bytesTotal > 0) {
                    formatFileSize(downloadItem.bytesTotal)
                } else {
                    "未知大小"
                }
                sizeTextView.text = sizeText

                // 设置日期（这里使用当前日期，实际应用中可能需要从下载项中获取）
                val dateFormat = SimpleDateFormat("yyyy-MM-dd HH:mm", Locale.getDefault())
                dateTextView.text = dateFormat.format(Date())

                // 设置进度条
                progressBar.progress = downloadItem.progress
                progressBar.visibility = if (downloadItem.status == DownloadManager.STATUS_RUNNING) {
                    View.VISIBLE
                } else {
                    View.GONE
                }

                // 设置操作按钮布局可见性
                actionsLayout.visibility = if (downloadItem.status == DownloadManager.STATUS_RUNNING ||
                    downloadItem.status == DownloadManager.STATUS_PAUSED) {
                    View.VISIBLE
                } else {
                    View.GONE
                }

                // 设置暂停/恢复按钮图标
                if (downloadItem.status == DownloadManager.STATUS_RUNNING) {
                    pauseResumeButton.setImageResource(android.R.drawable.ic_media_pause)
                    pauseResumeButton.contentDescription = "暂停"
                } else if (downloadItem.status == DownloadManager.STATUS_PAUSED) {
                    pauseResumeButton.setImageResource(android.R.drawable.ic_media_play)
                    pauseResumeButton.contentDescription = "恢复"
                }

                // 设置点击事件
                itemView.setOnClickListener {
                    if (downloadItem.status == DownloadManager.STATUS_SUCCESSFUL || downloadItem.fileExists) {
                        onItemClick(downloadItem)
                    }
                }

                pauseResumeButton.setOnClickListener {
                    if (downloadItem.status == DownloadManager.STATUS_RUNNING) {
                        onPauseClick(downloadItem)
                    } else if (downloadItem.status == DownloadManager.STATUS_PAUSED) {
                        onResumeClick(downloadItem)
                    }
                }

                deleteButton.setOnClickListener {
                    onDeleteClick(downloadItem)
                }
            }
        }
    }
}